const db = require('../config/database');

class CommentService {
  async create({ content, userId, momentId }) {
    const sql = `insert into comment set ?`;
    const para = { content, user_id: userId, moment_id: momentId };
    const [result] = await db.query(sql, para);
    return result;
  }
  async reply({ content, userId, momentId, commentId }) {
    const sql = `insert into comment set ?`;
    const para = {
      content,
      user_id: userId,
      moment_id: momentId,
      comment_id: commentId,
    };
    const [result] = await db.query(sql, para);
    return result;
  }
  async update(id, content) {
    const sql = `update comment set content = ? where id = ?;`;
    const [result] = await db.execute(sql, [content, id]);
    return result;
  }
  async remove(id) {
    const sql = `delete from comment where id = ?;`;
    const [result] = await db.execute(sql, [id]);
    return result;
  }

  async getCommentByMomentId({ momentId, pageSize, pageNumber }) {
    const offset = pageSize * (pageNumber - 1);
    const sql = `select c.id as id, c.content as content,c.comment_id as commentId,c.moment_id as momentId,
    json_object('id',u.id,'username',u.username) as commentUser
    from comment as c
    left join users as u on c.user_id = u.id
    where c.moment_id = ${momentId} limit ${offset} , ${pageSize};`;
    const [result] = await db.execute(sql, []);
    return result;
  }
}

module.exports = new CommentService();
